package com.cunshe.service;

import com.cunshe.common.FileUtil;
import com.cunshe.dao.ProductImageDao;
import com.cunshe.domain.ProductImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 产品图片
 * @author xiao
 */
@Service
public class ProductImageService {

    @Autowired
    private ProductImageDao productImageDao;

    /** 新增 */
    @Transactional(rollbackFor = Exception.class)
    public int insert(ProductImage record) {
        return productImageDao.insert(record);
    }

    /** 删除 */
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        ProductImage productImage = get(id);
        if(productImage == null){
            return 0;
        }
        int delete = productImageDao.delete(id);
        FileUtil.deleteFile(productImage.getUrl());

        return delete;
    }

    /** 删除 */
    @Transactional(rollbackFor = Exception.class)
    public int deleteByProductId(Long productId) {
        return productImageDao.deleteByProductId(productId);
    }

    /** 修改 */
    @Transactional(rollbackFor = Exception.class)
    public int update(ProductImage record) {
        return productImageDao.update(record);
    }

    /** 根据产品id查询 */
    public ProductImage get(Long id) {
        if(id == null) return null;
        return list(ProductImage.builder().id(id).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    /** 根据产品id查询 */
    public List<ProductImage> getProductImage(Long productId) {
        if(productId == null) return null;
        return list(ProductImage.builder().productId(productId).build());
    }

    /** 查询列表 */
    public List<ProductImage> list(ProductImage record) {
        return productImageDao.list(record);
    }

}